package com.householditemtwo.admin.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.householditemtwo.common.utils.BaseServlet;
import com.householditemtwo.common.utils.Result;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

@WebServlet("/admin/image")
public class ImageServlet extends BaseServlet {

    /**
     * 上传图片 - upload images
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void upload(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        PrintWriter out =response.getWriter();

        SmartUpload smart=new SmartUpload();
        smart.setCharset("utf-8");
        smart.initialize(getServletConfig(), request, response);
        try {
            smart.upload();
            smart.save("/images");
            String filename=smart.getFiles().getFile(0).getFileName();

            out.write(Result.toClient(0, "成功", null, filename));
        } catch (SmartUploadException e) {
            out.write(Result.toClient(10000, "失败", null, null));
            e.printStackTrace();
        }
        out.flush();
        out.close();
    }

}
